package cn.zxf.note.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * Created by zengxf on 2019/3/26.
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {

    private static final String
            KEY_MSG = "message",
            KEY_STATUS = "status",
            KEY_DEBUG = "debug-message",
            KEY_ERROR = "error";

    @ExceptionHandler(BizException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, Object> processBizException(BizException e) {
        String msg = String.format(e.errorMessage, e.params);
        log.warn("业务逻辑异常：{}", msg);
        Map<String, Object> json = Map.of(
                KEY_MSG, msg,
                KEY_STATUS, 400,
                KEY_ERROR, "Bad Request"
        );
        return json;
    }

    @ExceptionHandler(NoAuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Map<String, Object> processNoAuthException(NoAuthException e) {
        log.warn("认证异常！user-id: {}, type: {}", e.userId, e.type);
        Map<String, Object> json = Map.of(
                KEY_MSG, "未认证授权！",
                KEY_STATUS, 401,
                KEY_ERROR, "Unauthorized"
        );
        return json;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> processException(Exception e) {
        log.error("内部异常！", e);
        Map<String, Object> json = Map.of(
                KEY_MSG, "内部异常！",
                KEY_DEBUG, e.getMessage(),
                KEY_STATUS, 500,
                KEY_ERROR, "Internal Server Error"
        );
        return json;
    }

}
